<?php

declare(strict_types=1);

namespace app\common\command\proxy;

use app\common\worker\protocol\Framex;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use Workerman\Connection\AsyncTcpConnection;
use Workerman\Connection\TcpConnection;
use Workerman\Worker;

class Server extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('proxy:server')
            ->addArgument('action', Argument::OPTIONAL, "start|stop|restart|reload|status|connections", 'start')
            ->addOption('mode', 'm', Option::VALUE_OPTIONAL, 'Run the workerman server in daemon mode.')
            ->setDescription('the proxy:server command');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $output->writeln('proxy:server');


        $action = $input->getArgument('action');
        $mode = $input->getOption('mode');


        // 重新构造命令行参数,以便兼容workerman的命令
        global $argv;

        $argv = [];

        array_unshift($argv, 'think', $action);

        if ($action == 'restart') {
            $mode = 'd';
        }

        if ($mode == 'd') {
            $argv[] = '-d';
        } else if ($mode == 'g') {
            $argv[] = '-g';
        }

        $worker = new Worker('tcp://0.0.0.0:4457');

        $worker->protocol = Framex::class;

        $worker->onConnect = function (TcpConnection $client_connection) {
            // Async TCP connection.
            $remote_connection = new AsyncTcpConnection("tcp://127.0.0.1:4456");
            $remote_connection->pipe($client_connection);
            $client_connection->pipe($remote_connection);
            $remote_connection->connect();
        };

        Worker::runAll();
    }
}
